<script setup lang="ts">
import { ref } from "vue";
import { importData } from "@/api/base";
import { downloadByUrl } from "@pureadmin/utils";
import fileIcon from "~icons/ri/upload-cloud-fill";
import type { UploadInstance } from "element-plus";
import { message } from "@/utils/message";
import file from "@/assets/templete/material.xlsx";

const downloadTemplate = async () => {
  downloadByUrl(file, "物料模板.xlsx");
};

const emit = defineEmits(["close"]);

const upload = ref<UploadInstance>();
const handleChange = async e => {
  errorList.value = [];
  const formData = new FormData();
  formData.append("file", e.raw);
  const res = await importData("Material", formData);
  if (!res.success) {
    upload.value!.clearFiles();
    errorList.value = res.ErrorList;
  } else {
    message("导入成功", { type: "success" });
    emit("close");
  }
};
const errorList = ref([]);
</script>

<template>
  <div>
    <el-row :gutter="20">
      <el-col :sm="24" :md="24">
        <el-button type="primary" @click="downloadTemplate">下载模板</el-button>
      </el-col>
    </el-row>
    <el-upload
      ref="upload"
      class="upload-demo"
      accept=".xlsx,.xls"
      drag
      :multiple="false"
      :on-change="handleChange"
      :auto-upload="false"
    >
      <el-icon class="el-icon--upload">
        <IconifyIconOffline :icon="fileIcon" />
      </el-icon>
      <div class="el-upload__text">可点击或拖拽上传</div>
    </el-upload>
    <!-- 错误提示区域 -->
    <el-alert
      v-if="errorList.length"
      title="数据校验错误"
      type="error"
      :closable="false"
      show-icon
      class="error-list"
    >
      <el-scrollbar max-height="200px">
        <ul class="error-items">
          <li v-for="(err, index) in errorList" :key="index">
            {{ err }}
          </li>
        </ul>
      </el-scrollbar>
    </el-alert>
  </div>
</template>
